import librosa
import numpy as np
from PIL import Image

# 加载音频文件
audio_path = '葡萄牙语打开1.wav'  # 替换为你的音频文件路径
y, sr = librosa.load(audio_path, sr=None)  # 加载音频文件

# 计算响度（以分贝为单位）
loudness = librosa.feature.rms(y=y)**2  # RMS的平方，因为响度通常与功率成正比

# 归一化响度数据到0-255的范围
loudness_normalized = (loudness - np.min(loudness)) / (np.max(loudness) - np.min(loudness)) * 255
loudness_normalized = loudness_normalized.astype(np.uint8)  # 转换为整数

# 将一维响度数组转换为224*224的二维数组
image_size = 224
loudness_image = np.zeros((image_size, image_size), dtype=np.uint8)
loudness_image.flat = loudness_normalized  # 将归一化的响度数据填充到二维数组中
loudness_image = loudness_image.reshape((image_size, image_size))

# 将numpy数组转换为PIL图像
image = Image.fromarray(loudness_image, 'L')

# 保存图片
image.save('ptg_loudness_image.png')

# 显示图片
image.show()